const { ipcRenderer } = require('electron');

function formatJSON(obj) {
  if (obj && Array.isArray(obj?.args)) {
    const date = new Date(obj.timestamp);
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');
    const milliseconds = Math.floor(date.getMilliseconds() / 100);
    const timestamp = `${hours}:${minutes}:${seconds}.${milliseconds}`;
    const type = obj.type || 'log';
    
    if (type === 'log' || type === 'debug') {
      const formattedArgs = obj.args.map(arg => {
        if (arg.type === 'string') {
          return arg.value || arg;
        } else if (arg.type === 'object' && arg.preview && Array.isArray(arg.preview.properties)) {
          return arg.preview.properties.map(prop => 
            `${prop.name}: ${prop.value.value || prop.value}`
          ).join('\n');
        } else if (arg && Array.isArray(arg.properties)) {
          const formattedProps = {};
          for (const prop of arg.properties) {
            if (prop.name && prop.value) {
              formattedProps[prop.name] = prop.value.value || prop.value;
            }
          }
          return formattedProps;
        }
        return arg.value || arg;
      });

      return {
        timestamp,
        type,
        content: formattedArgs.length === 1 ? formattedArgs[0] : formattedArgs.join('\n')
      };
    }

    return {
      timestamp,
      type,
      content: obj.params.args.map(arg => arg.value || arg).join('\n')
    };
  }
  return '';

}

function createMessageElement(message) {
  const formatted = formatJSON(message);
  const messageDiv = document.createElement('div');
  
  if (formatted.type) {
    messageDiv.className = `message ${formatted.type}`;
    
    const timestampSpan = document.createElement('span');
    timestampSpan.className = 'timestamp';
    timestampSpan.textContent = `[${formatted.timestamp}] `;
    
    const contentPre = document.createElement('pre');
    contentPre.textContent = JSON.stringify(formatted.content, null, 2);
    
    messageDiv.appendChild(timestampSpan);
    messageDiv.appendChild(contentPre);
  } else {
    messageDiv.className = 'message system';
    const contentPre = document.createElement('pre');
    contentPre.textContent = JSON.stringify(formatted, null, 2);
    messageDiv.appendChild(contentPre);
  }
  
  return messageDiv;
}

const output = document.getElementById('output');
const eventFilter = document.getElementById('eventFilter');

eventFilter.addEventListener('input', (e) => {
  const filterText = e.target.value.toLowerCase();
  const messages = output.getElementsByClassName('message');
  
  Array.from(messages).forEach(message => {
    const contentPre = message.querySelector('pre');
    if (contentPre) {
      try {
        const content = contentPre.textContent.toLowerCase();
        message.style.display = filterText === '' || content.includes(filterText) ? 'block' : 'none';
      } catch (err) {
        console.error('Error parsing message content:', err);
        message.style.display = 'none';
      }
    }
  });
});

// 监听主进程发送的CDP消息
ipcRenderer.on('cdp-message', (event, message) => {
  console.log('[Debug] 收到CDP消息:', message);
  if (!message) {
    console.error('[Error] 收到空消息');
    return;
  }
  
  const messageElement = createMessageElement(message);
  output.insertBefore(messageElement, output.firstChild);
});
